import { ElMessage } from "element-plus";
import { defineStore } from "pinia"; // 5.从pinia里面引入defineStore

// 7.类型
interface useLonginType {
  name: string | null;
  token: string | null;
  timer: null | any;
  isShowLoginDialog: boolean;
}

// 6.创建pinia仓库                         起别名
const useLonginStore = defineStore("useLongin", {
  //state建议书写为箭头函数,方便书写ts类型
  // 8.引入类型
  state: (): useLonginType => {
    return {
      // 所有这些属性都将自动推断其类型
      isShowLoginDialog: false, // 是否显示登录弹框

      name: localStorage.getItem("name"), //用户信息
      token: localStorage.getItem("token"), //初始值看看本地有没有token
      timer: 0, //轮询定时器
      // menuRoutes: staticRoutes,  // 路由菜单
    };
  },
  actions: {
    // 设置token
    set_Token(token: string) {
      return localStorage.setItem("token", token);
    },
    //删除token
    remove_Token() {
      return localStorage.removeItem("token");
    },
    //设置用户信息
    set_UserInfo(name: string) {
      localStorage.setItem("name", name);
      this.name = name;
    },
    // 删除用户信息
    remove_UserInfo(name: string) {
      localStorage.removeItem(name);
      this.name = "";
    },
    // 轮询检测用户是否登录
    async queryLoginStatus() {
      this.timer = setInterval(() => {
        console.log("轮询检测中");
        if (localStorage.getItem("token")) {
          const name = localStorage.getItem("name");
          const token = localStorage.getItem("token");
          this.set_Token(token as string);
          this.set_UserInfo(name as string);
          clearInterval(this.timer); // 清除定时器
          this.isShowLoginDialog = false; // 关闭登录框
          ElMessage.success("登录成功");
        }
      }, 1000);
    },
    // 控制弹窗
    ShowLoginDialog(type: boolean) {
      this.isShowLoginDialog = type;
    },
  },
  getters: {},
});

export default useLonginStore;
